package class07;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

// 测试链接：https://leetcode.com/problems/binary-tree-level-order-traversal-ii
public class MyCode01_BinaryTreeLevelOrderTraversalII {

	public static class TreeNode {
		public int val;
		public TreeNode left;
		public TreeNode right;

		TreeNode(int val) {
			this.val = val;
		}
	}

	public List<List<Integer>> levelOrderBottom(Code01_BinaryTreeLevelOrderTraversalII.TreeNode root) {
		List<List<Integer>> ans = new LinkedList<>();//最终结果存放数组
		if (root == null) {
			return ans;
		}
		Queue<Code01_BinaryTreeLevelOrderTraversalII.TreeNode> queue = new LinkedList<>();
		queue.add(root);//根节点加到队列
		while (!queue.isEmpty()) {
			int size = queue.size();//队列中元素的数量
			List<Integer> curAns = new LinkedList<>();
			for (int i = 0; i < size; i++) {
				Code01_BinaryTreeLevelOrderTraversalII.TreeNode curNode = queue.poll();//依次弹出本行的节点
				curAns.add(curNode.val);//往数组中添加
				if (curNode.left != null) {
					queue.add(curNode.left);//把二叉树的左分支添加到队列，意思是把下一行的数据加到队列中
				}
				if (curNode.right != null) {
					queue.add(curNode.right);//把二叉树的右分支添加到队列，意思是把下一行的数据加到队列中
				}
			}
			ans.add(0, curAns);
		}
		return ans;
	}

}
